package com.lidong.framework.service;

import java.io.Serializable;
import java.util.List;

import com.lidong.framework.model.BasePojo;
import com.lidong.framework.model.Grid;
import com.lidong.framework.model.QueryPojo;
import com.lidong.framework.mybatis.query.ConditionQuery;
import com.lidong.framework.mybatis.query.condition.Condition;
import com.lidong.framework.dal.SchDao;
import org.springframework.beans.factory.annotation.Autowired;

public class SchService<T extends BasePojo, Dao extends SchDao<T>>{
	
	protected Dao dao;

	@Autowired
	public void setDao(Dao dao) {
		this.dao = dao;
	}

	/**
	 * 主键查询
	 * @param id
	 * @return
	 */
	public T get(Serializable id) {
		return dao.get(id);
	}

	public List<T> queryAll(){
		return dao.query(new ConditionQuery());
	}

	public List<T> query(ConditionQuery query){
		return dao.query(query);
	}

	public int queryCnt(ConditionQuery query){
		return dao.queryCnt(query);
	}

	public List<T> query(QueryPojo queryPojo) {
		ConditionQuery query = queryPojo.buildConditionQuery();
		return this.query(query);
	}

	public int queryCnt(QueryPojo queryPojo) {
		ConditionQuery query = queryPojo.buildConditionQuery();
		return dao.queryCnt(query);
	}

	public List<T> query(QueryPojo queryPojo, List<Condition> conditions) {
		ConditionQuery query = queryPojo.buildConditionQuery();
		if (null != conditions && conditions.size() > 0) {
			query.addAll(conditions);
		}
		return this.query(query);
	}

	public int queryCnt(QueryPojo queryPojo, List<Condition> conditions) {
		ConditionQuery query = queryPojo.buildConditionQuery();
		if (null != conditions && conditions.size() > 0) {
			query.addAll(conditions);
		}
		return dao.queryCnt(query);
	}

	/**
	 * 分页
	 * @param grid
	 * @param query
	 * @return
	 */
	public Grid listGrid(Grid grid, ConditionQuery query){
		int count = this.queryCnt(query);
		if(count > 0){
			grid.setCount(count);
			grid.setData(this.query(query));
		}
		return grid;
	}

	public Grid listGrid(Grid grid) {
		ConditionQuery query = grid.buildConditionQuery();
		return this.listGrid(grid, query);
	}

	public Grid listGrid(Grid grid, List<Condition> appendConditions) {
		ConditionQuery query = grid.buildConditionQuery();
		if (null != appendConditions && appendConditions.size() > 0) {
			query.addAll(appendConditions);
		}
		return this.listGrid(grid, query);
	}
}
